package com.bite.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.domain.R;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.enums.UserIdentity;
import com.bite.common.security.exception.ServiceException;
import com.bite.common.security.service.TokenService;
import com.bite.system.domain.dto.LoginDTO;
import com.bite.system.domain.SysUser;
import com.bite.system.domain.dto.SysUserSaveDTO;
import com.bite.system.mapper.SysUserMapper;
import com.bite.system.service.ISysUserService;
import com.bite.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.bite.common.core.enums.ResultCode.FAILED_LOGIN;
import static com.bite.common.core.enums.ResultCode.FAILED_USER_NOT_EXISTS;


@Service
@RefreshScope //动态更新
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    @Override
    public R<String> login(LoginDTO loginDTO) {
        //通过账号去数据库里查询对应的用户信息
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(SysUser::getUserId,SysUser::getPassword)
                .eq(SysUser::getUserAccount, loginDTO.getUserAccount())
        );
        //用户不存在
        if (sysUser == null){
            return R.fail(FAILED_USER_NOT_EXISTS);
        }
        //密码校验通过
        if (BCryptUtils.matchesPassword(loginDTO.getPassword(), sysUser.getPassword())){
            String token = tokenService.
                    createToken(sysUser.getUserId(), secret, UserIdentity.ADMIN.getValue());
            return R.ok(token);
        }
        //密码错误
        return R.fail(FAILED_LOGIN);
    }

    @Override
    public int add(SysUserSaveDTO saveDTO) {
        //首先判断要添加的用户是否已经存在了
        List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserAccount, saveDTO.getUserAccount()));
        if (CollectionUtil.isNotEmpty(sysUsers)){
            // 返回的结果不为空，说明用户已经存在了
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }
        //将DTO转换为实体对象
        SysUser sysUser = new SysUser();
        sysUser.setUserAccount(saveDTO.getUserAccount());
        //将传递来的明文密码，加密存储到数据库中
        String password = BCryptUtils.encryptPassword(saveDTO.getPassword());
        sysUser.setPassword(password);
        //createBy等字段被MP自动填充
        //插入数据库
        return sysUserMapper.insert(sysUser);

    }

}
